$(function () {

    var courseId;
    /**
     *  解析url  的参数
     */
    function queryURLparams() {
        var url = window.location.href;
        var obj = {}
        if (url.indexOf('?') < 0) return obj
        var arr = url.split('?')
        url = arr[1]
        var array = url.split('&')
        for (var i = 0; i < array.length; i++) {
            var arr2 = array[i]
            var arr3 = arr2.split('=')
            obj[arr3[0]] = arr3[1]
        }

        var id = obj.id;
        courseId=obj.id;
        $.get(baseURL + "sys/jxcourse/info/" + id, function (r) {
            vm.jxcourse = r.jxCourse;
            console.log(r);
            $("#lab_name").text(r.jxCourse.name);
        });
        return  obj;
    }

   var obj= queryURLparams();   //  解析url参数
    vm.sc=obj.id?true:false;

    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/jxstudyfile/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true},
            {label: '资料名称', name: 'fileName', index: 'fileName', width: 80},
            {label: '文件分类', name: 'fileType', index: 'fileType', width: 80 ,formatter: function (cellvalue, options, rowObject) {
                    return cellvalue=="0"?"非视频文件":"视频文件"
                },},
            {label: '文件地址', name: 'id', index: 'id', width: 80,formatter: function (cellvalue, options, rowObject) {
                    return "<a class='btn btn-default ' onclick='downloadFile("+cellvalue+")' ><i class='fa fa-download' style='font-size: 20px'></i>&nbsp;下载</a>";
    },},
            {label: '文件后缀', name: 'filePostfix', index: 'filePostfix', width: 80},
            {label: '资料介绍', name: 'fileDesc', index: 'fileDesc', width: 80},
            {label: '对应课程', name: 'courseName', index: 'courseName', width: 80},
            {label: '排序', name: 'orderNum', index: 'orderNum', width: 80}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        shrinkToFit:true,
        autoScroll: true,
        pager: "#jqGridPager",
        postData: {'courseId': courseId, 'courseName': vm.q.courseName},
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
           // $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "scroll"});
        }
    });


    new AjaxUpload('#upload', {
        action: baseURL + "sys/oss/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){

            if(vm.jxStudyFile.fileType=="1"){  // 视频
                if (!(extension && /^(mp4|avi|rmvb|flv)$/.test(extension.toLowerCase()))){
                    alert('请上传视频文件');
                    return false;
                }
            }else{   // 非视频
               /* if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                    alert('请上传非视频文件！');
                    return false;
                }*/
            }
            layer.load('努力上传中', {
                shade: [0.3,'#fff'] //0.1透明度的白色背景
            });

        },
        onComplete : function(file, r){
            layer.closeAll('loading');
            if(r.code == 0){
                alert(r.url);
                vm.jxStudyFile.fileUrl=r.url;
                if(vm.jxStudyFile.fileType=="1"){ // 视频
                  vm.showVideo=false;
                  $("#video").attr("src",r.url);
                }else{ //  非视频

                }

            }else{
                alert(r.msg);
            }
        }
    });
});


var loading;  // 缓冲效果

var vm = new Vue({
    el: '#rrapp',
        data: {
            q: {
                courseName: null
            },
            sc:true,
            showList: true,
            title: null,
            showVideo: true,
            jxCourse: {},
            jxStudyFile: {}
        },
        methods: {
            query: function () {
                vm.reload();
            },
            add: function () {
                vm.showList = false;
                vm.showVideo = true;
                    vm.title = "新增";
                vm.jxStudyFile = {courseId: vm.jxCourse.id};
            },
            update: function (event) {
                var id = getSelectedRow();
                if (id == null) {
                    return;
                }
                vm.showList = false;
                vm.showVideo = true;
                vm.title = "修改";

                vm.getInfo(id)
            },
            saveOrUpdate: function (event) {
                vm.jxStudyFile.courseId=vm.jxcourse.id;
                $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function () {
                    var url = vm.jxStudyFile.id == null ? "sys/jxstudyfile/save" : "sys/jxstudyfile/update";
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(vm.jxStudyFile),
                        success: function (r) {
                            if (r.code === 0) {
                                layer.msg("操作成功", {icon: 1});
                                vm.reload();
                                $('#btnSaveOrUpdate').button('reset');
                                $('#btnSaveOrUpdate').dequeue();
                            } else {
                                layer.alert(r.msg);
                                $('#btnSaveOrUpdate').button('reset');
                                $('#btnSaveOrUpdate').dequeue();
                            }
                        }
                    });
                });
            },
            del: function (event) {
                var ids = getSelectedRows();
                if (ids == null) {
                    return;
                }
                var lock = false;
                layer.confirm('确定要删除选中的记录？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    if (!lock) {
                        lock = true;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "sys/jxstudyfile/delete",
                            contentType: "application/json",
                            data: JSON.stringify(ids),
                            success: function (r) {
                                if (r.code == 0) {
                                    layer.msg("操作成功", {icon: 1});
                                    $("#jqGrid").trigger("reloadGrid");
                                } else {
                                    layer.alert(r.msg);
                                }
                            }
                        });
                    }
                }, function () {
                });
            },
            getInfo: function (id) {
                $.get(baseURL + "sys/jxstudyfile/info/" + id, function (r) {
                    console.log(r);
                    vm.jxStudyFile = r.jxStudyFile;
                    if(vm.jxStudyFile.fileType=="0"){  //  视频
                        vm.showVideo=false;
                        $("#video").attr("src",vm.jxStudyFile.fileUrl);
                    }
                });
            },
            reload: function (event) {
                vm.showList = true;
                var page = $("#jqGrid").jqGrid('getGridParam', 'page');
                $("#jqGrid").jqGrid('setGridParam', {
                    page: page,
                    postData: {'courseId': vm.jxcourse.id, 'courseName': vm.q.courseName}

                }).trigger("reloadGrid");
            }
        }
});

function downloadFile(id) {   //   下载模板
    $.get(baseURL + "sys/jxstudyfile/info/"+id, function(r){
        vm.jxStudyFile = r.jxStudyFile;
        var url = baseURL + "sys/jxstudenthomwork/downFile?fileUrl="+r.jxStudyFile.fileUrl+"&&path=studyFile";
        window.open(url);
    });
}